process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

let all = null;
// const { exec } = require('child_process');
const https = require('https');
// const WebSocket = require('ws');
const express = require('express')
const app = express()

app.get('/', (req, res) => {
    res.send('Hello World!')
})
const cors = function (req, res, next) {
    // console.log('LOGGED')
    // get 方法会自动添加，其他方法需要手动添加
    res.set({
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "POST, GET, PUT, OPTIONS, DELETE",
        "Access-Control-Allow-Headers": "authorization,Content-Type"
    })
    next()
}
app.use(cors)

// const findLeagueClientCommandLine = async () => {
//     return new Promise((resolve, reject) => {
//         exec('"C:\\Windows\\System32\\wbem\\wmic" PROCESS WHERE "name=\'LeagueClientUx.exe\'" GET commandline', (err, stdout) => {
//             if (err) {
//                 reject(err);
//             } else {
//                 all = stdout;
//                 resolve(stdout);
//             }
//         });
//     });
// };

// findLeagueClientCommandLine();


const getRiotData = async (url) => {
    // const token = all.match(/remoting-auth-token=(.*?)["'\s]/)[1]
    // const port = all.match(/--app-port=(.*?)["'\s]/)[1]
    // const auth = Buffer.from(`riot:${token}`).toString('base64');
    const port = all.port
    const auth = all.token
    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Basic ${auth}`
    };
    const options = {
        hostname: '127.0.0.1',
        port: port,
        path: url,
        method: 'GET',
        headers: headers
    };
    return new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
            let data = '';
            res.on('data', (chunk) => {
                data += chunk;
            });
            res.on('end', () => {
                resolve(data);
            });
        });
        req.on('error', (error) => {
            reject(error);
        });
        req.end();
    })
};
const postRiotData = async (url, data, method) => {
    const port = all.port
    const auth = all.token
    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Basic ${auth}`
    };
    const options = {
        hostname: '127.0.0.1',
        port: port,
        path: url,
        method: method,
        headers: headers
    };
    if (data != null) {
        // post请求携带的数据需要格式化
        const data1 = JSON.stringify(data)
        return new Promise((resolve, reject) => {
            const req = https.request(options, (res) => {
                let data = '';
                res.on('data', (chunk) => {
                    data += chunk;
                });
                res.on('end', () => {
                    resolve(data);
                });
            });
            req.on('error', (error) => {
                reject(error);
            });
            req.write(data1)
            req.end();
        })
    } else {
        return new Promise((resolve, reject) => {
            const req = https.request(options, (res) => {
                let data = '';
                res.on('data', (chunk) => {
                    data += chunk;
                });
                res.on('end', () => {
                    resolve(data);
                });
            });
            req.on('error', (error) => {
                reject(error);
            });
            req.end();
        })
    }

};

app.use('/sendRotData', async (req, res) => {
    try {
        all = req.query
        console.log(all);
        res.send('收到')
    } catch (error) {
        console.error('sendRotData发生错误:', error);
    }
})

app.use('/getAbc', async (req, res) => {
    try {
        res.send('abc')
    } catch (error) {
        res.send('测试方法失败')
        console.error('getAbc:', error);
    }
})

app.use('/getUserInfo', async (req, res) => {
    try {
        const currentUser = await getRiotData('/lol-summoner/v1/current-summoner');
        console.log('当前获取到的用户数据:', currentUser);
        res.send(currentUser)
    } catch (error) {
        res.send('获取不到用户信息')
        console.error('getUserInfo发生错误:', error);
    }
})

app.use('/getUserState', async (req, res) => {
    try {
        const data = await getRiotData('/lol-gameflow/v1/gameflow-phase');
        // console.log('当前获取到当前玩家状态:', data);
        res.send(data)
    } catch (error) {
        res.send('offline')
        console.error('getUserState发生错误:', error);
    }
})

app.use('/postaccept', async (req, res) => {
    try {
        const data = await postRiotData('/lol-matchmaking/v1/ready-check/accept', req.query, 'POST');
        console.log('接受对局成功', data);
        res.send(data)
    } catch (error) {
        res.send('接受对局失败')
        console.error('postaccept发生错误:', error);
    }
})

app.use('/getActionId', async (req, res) => {
    try {
        const data = await getRiotData('/lol-champ-select/v1/session');
        res.send(data)
    } catch (error) {
        console.error('getActionId发生错误:', error);
    }
})

app.use('/patchrole', async (req, res) => {
    try {
        // 需要在url后面拼接上位置的id
        let actionId = parseInt(req.query.actionId)
        const data = await postRiotData('/lol-champ-select/v1/session/actions/' + actionId, req.query, 'PATCH');
        res.send(data)
    } catch (error) {
        res.send('秒选英雄失败')
        console.error('patchrole发生错误:', error);
    }
})

app.use('/postrole', async (req, res) => {
    try {
        // 需要在url后面拼接上位置的id
        let actionId = parseInt(req.query.actionId)
        const data = await postRiotData('/lol-champ-select/v1/session/actions/' + actionId + '/complete', req.query, 'POST');
        res.send(data)
    } catch (error) {
        res.send('秒选英雄确定失败')
        console.error('patchrole发生错误:', error);
    }
})




app.listen(9133, async () => {
    console.log('运行在 http://127.0.0.1:9133');
})
